#!/bin/bash
DVD='java -cp bin DVDSystem '
CLEAN='make testclean'
MAKE='make'
TESTDIR='tests'

# declare an array for the names of the test dirs
declare -a TDIRS

# clean the tests and make the project
$CLEAN
$MAKE

# counter for loops
COUNTER=0

# find all test group directories
for i in $( ls $TESTDIR ); do
	echo $COUNTER = $i
	TDIRS[$COUNTER]=$i
	((COUNTER++))
done

COUNTER=0

# promt for which test groups to run
echo "Enter the numbers of the tests to run seperated by spaces (ENTER for all)":
# read in array of numbers
read -a SEL
echo -n Selected:
# if first element is non-null select those dirs else select all dirs
if [[ -n "$SEL" ]]
then
	for j in ${SEL[*]}; do
		SELECTED[$COUNTER]=${TDIRS[${SEL[$COUNTER]}]}
		echo -n " ${SELECTED[$COUNTER]}"
		((COUNTER++))
	done
else
	for j in ${TDIRS[*]}; do
		SELECTED[$COUNTER]=$j
		echo -n " ${SELECTED[$COUNTER]}"
		((COUNTER++))
	done
fi
echo

COUNTER=0

# for each folder selected
for k in ${SELECTED[*]}; do
	echo -e '\E[48;33m'"\033[1mTests in $k:\033[0m"
	CURRENTDIR=$TESTDIR'/'$k'/'
	for l in $(ls $TESTDIR/$k | grep .txt | sed 's/\(.*\)\..*/\1/'); do
		echo -n "$l:"
		
		# make sure idf (input transaction) file exists and create empty one if it doesn't
		touch $CURRENTDIR$l'.idf'
		
		# set the run string
		RUN=$DVD$CURRENTDIR$l'.idf'' '$CURRENTDIR$l'.dtf'
		
		# run the command (piping in the test .txt file) and pipe all output to the .ato file
		$RUN < $CURRENTDIR$l'.txt' &> $CURRENTDIR$l'.ato'

		# diff the console output/expected files and save the return value
		diff -C3 --strip-trailing-cr $CURRENTDIR$l'.ato' $CURRENTDIR$l'.bto' &> $CURRENTDIR$l'.bto.diff'
		RETTERM=$?

		# diff the transaction output/expected files and save the return value
		diff -C3 --strip-trailing-cr $CURRENTDIR$l'.dtf' $CURRENTDIR$l'.etf' &> $CURRENTDIR$l'.etf.diff'
		RETTRAN=$?
		

		## test for each condition:
			# both terminal and transaction log PASS
			# both terminal and transaction log FAIL
			# terminal FAIL but transaction log PASS
			# terminal PASS but transaction log FAIL
			# either diff failed on having a missing input file

		if [[ RETTERM -eq 0 && RETTRAN -eq 0 ]]
		then
			echo -e '\E[48;32m'"\033[1mPASSED\033[0m"
			rm $CURRENTDIR$l'.bto.diff' $CURRENTDIR$l'.etf.diff'
		fi

		if [[ RETTERM -eq 1 && RETTRAN -eq 1 ]]
		then
			echo -e '\E[48;31m'"\033[1mFAILED\033[0m"
		fi

		if [[ RETTERM -eq 0 && RETTRAN -eq 1 ]]
		then
			echo -e -n '\E[48;31m'"\033[1mFAILED\033[0m"
			echo " - PASSED TERMINAL"
			rm $CURRENTDIR$l'.bto.diff'
		fi

		if [[ RETTERM -eq 1 && RETTRAN -eq 0 ]]
		then
			echo -e -n '\E[48;31m'"\033[1mFAILED\033[0m"
			echo " - PASSED TRANSACTION"
			rm $CURRENTDIR$l'.etf.diff'
		fi

		if [[ RETTERM -eq 2 || RETTRAN -eq 2 ]]
		then
			echo -e '\E[48;33m'"\033[1mDIFF FAILED\033[0m"
		fi
	done
done